<template>
  <!-- 菜单权限管理页面 -->
  <div class="menu-manage">
    <!-- 菜单树结构卡片 -->
    <el-card class="menu-tree-card" shadow="hover">
      <h1 style="color: #3998a9;">菜单管理</h1>
      <!-- 菜单树组件 -->
      <el-tree :data="menuStore.menuList" :props="treeProps" node-key="id" highlight-current draggable
        @node-drop="handleDrop" @node-click="handleEdit" :expand-on-click-node="false" :default-expand-all="true"
        v-loading="menuStore.loading">
        <!-- 自定义菜单项模板 -->
        <template #default="{ data }">
          <div class="menu-item-row" @mouseenter="data._hover = true" @mouseleave="data._hover = false">
            <!-- 菜单标题和图标 -->
            <span style="display: flex; align-items: center;">
              <el-icon v-if="data.icon" style="margin-right:4px">
                <component :is="data.icon" />
              </el-icon>
              {{ data.menuname }}
              <span class="menu-path">({{ data.path }})</span>
              <!-- <span v-if="!data.isActive" class="menu-disabled-tag">已禁用</span> -->
            </span>
            <!-- 菜单操作按钮 -->
            <span class="menu-actions">
              <el-button size="small" :type="data.isActive ? 'success' : 'info'" plain
                @click.stop="handleToggleStatus(data)" style="margin-right: 8px; min-width: 60px; font-weight:bold;"
                :title="data.isActive ? '点击禁用' : '点击启用'">
                <el-icon style="vertical-align:middle;margin-right:2px;">
                  <component :is="data.isActive ? 'Check' : 'Close'" />
                </el-icon>
                {{ data.isActive ? '已启用' : '已禁用' }}
              </el-button>

              <el-button type="primary" size="small" @click.stop="handleEdit(data)" style="font-weight:bold;">
                <el-icon style="vertical-align:middle;margin-right:2px;">
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button v-show="data._hover" type="danger" size="small" @click.stop="handleDelete(data)"
                class="delete-button">
                删除
              </el-button>
            </span>
          </div>
        </template>
      </el-tree>
      <el-button type="primary" style="margin-top:12px;" @click="handleAdd" class="add-button">
        <el-icon style="vertical-align:middle;margin-right:2px;">
          <Plus />
        </el-icon>
        新增菜单
      </el-button>
    </el-card>

    <!-- 菜单表单抽屉 -->
    <el-drawer v-model="drawerVisible" :title="editMode ? '编辑菜单' : '新增菜单'" size="420px" direction="rtl"
      :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="menuForm" label-width="90px" style="max-width:400px; margin-top:16px;">
        <el-form-item label="菜单名称" prop="menuname">
          <el-input v-model="form.menuname" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入菜单路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="form.icon" placeholder="请选择图标">
            <el-option v-for="icon in iconOptions" :key="icon" :label="icon" :value="icon">
              <el-icon>
                <component :is="icon" />
              </el-icon>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 父级菜单选择 -->
        <el-form-item label="父级菜单" prop="parentId">
          <el-cascader v-model="form.parentId" :options="cascaderOptions"
            :props="{ value: 'id', label: 'menuname', children: 'children', checkStrictly: true }" clearable
            placeholder="请选择父级菜单" style="width:100%" @change="handleParentChange" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="menuStore.loading">
            {{ editMode ? '保存' : '创建' }}
          </el-button>
          <el-button @click="handleCancel" class="cancel-button">
            <el-icon style="vertical-align:middle;margin-right:2px;">
              <Close />
            </el-icon>
            取消
          </el-button>
          <el-button @click="resetForm" class="reset-button">
            <el-icon style="vertical-align:middle;margin-right:2px;">
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Close, Refresh, Plus } from '@element-plus/icons-vue'
import { useMenuStore } from '@/stores/menuStore'

// 使用菜单状态管理
const menuStore = useMenuStore()

// 图标选项
const iconOptions = [
  'Monitor', 'Setting', 'User', 'Edit', 'Folder', 'Avatar', 'Tools', 'Document', 'House'
]

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'menuname'
}

// 表单数据
const form = reactive({
  id: null,
  menuname: '',
  path: '',
  icon: '',
  parentId: null,
  sort: 1,
  isActive: true
})

// 表单验证规则
const rules = {
  menuname: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 响应式数据
const drawerVisible = ref(false)
const editMode = ref(false)
const menuForm = ref(null)

// 页面加载时获取菜单数据
onMounted(() => {
  menuStore.fetchMenuTree()
})

// 新增菜单
function handleAdd() {
  editMode.value = false
  resetForm()
  drawerVisible.value = true
}

// 编辑菜单
function handleEdit(data) {
  editMode.value = true
  Object.assign(form, {
    id: data.id,
    menuname: data.menuname,
    path: data.path,
    icon: data.icon,
    parentId: data.parentId,
    sort: data.sort,
    isActive: data.isActive
  })
  drawerVisible.value = true
}

// 删除菜单
async function handleDelete(data) {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${data.menuname}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await menuStore.removeMenu(data.id)
  } catch (error) {
    // 用户取消删除
    console.log('删除操作已取消', error)
  }
}

// 拖拽处理
function handleDrop(draggingNode, dropNode, dropType, ev) {
  // 这里可以添加拖拽排序的逻辑
  // 暂时只显示提示，不进行实际操作
  ElMessage.info('拖拽功能暂未实现')
}

// 保存/创建菜单
async function submitForm() {
  try {
    await menuForm.value.validate()

    // 修复：正确处理 ID 字段
    const menuData = {
      id: form.id || '00000000-0000-0000-0000-000000000000', // 新增时使用空 GUID
      menuname: form.menuname,
      path: form.path,
      icon: form.icon,
      parentId: form.parentId,
      sort: form.sort,
      isActive: form.isActive
    }

    // console.log('提交的菜单数据:', menuData)

    const success = await menuStore.saveMenu(menuData)
    if (success) {
      // 刷新所有菜单数据，确保布局组件菜单栏及时更新
      await menuStore.refreshAllMenus()

      resetForm()
      drawerVisible.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 重置表单
function resetForm() {
  Object.assign(form, {
    id: null,
    menuname: '',
    path: '',
    icon: '',
    parentId: null,
    sort: 1,
    isActive: true
  })
  editMode.value = false
  nextTick(() => menuForm.value && menuForm.value.clearValidate())
}

// 转换菜单树为级联选择器格式
const cascaderOptions = computed(() => {
  function transformTreeToCascader(tree) {
    return tree.map(item => ({
      id: item.id,
      menuname: item.menuname,
      children: item.children && item.children.length ? transformTreeToCascader(item.children) : undefined
    }))
  }
  return transformTreeToCascader(menuStore.menuList)
})

// 父级菜单变更处理
function handleParentChange(value) {
  if (value.length === 0) {
    form.parentId = null
  } else {
    form.parentId = value[value.length - 1]
  }
}
// 取消操作：关闭抽屉不重置表单
function handleCancel() {
  drawerVisible.value = false;
}
// 切换菜单启用/禁用状态
async function handleToggleStatus(data) {
  try {
    // 先切换本地状态，提供即时反馈
    const newStatus = !data.isActive;
    data.isActive = newStatus;

    const menuData = {
      id: data.id,
      menuname: data.menuname,
      path: data.path,
      icon: data.icon,
      parentId: data.parentId,
      sort: data.sort,
      isActive: newStatus
    };

    await menuStore.saveMenu(menuData);

    // 刷新所有菜单数据，确保布局组件菜单栏及时更新
    // console.log('开始刷新所有菜单数据...');
    await menuStore.refreshAllMenus();
    // console.log('菜单数据刷新完成');

    // 延迟一下，确保数据更新完成
    await new Promise(resolve => setTimeout(resolve, 100));

    // 强制重新获取用户菜单数据
    await menuStore.fetchUserMenuTree();
    // console.log('用户菜单数据已重新获取');

    ElMessage.success(newStatus ? '菜单已启用' : '菜单已禁用');
  } catch (error) {
    console.error('切换菜单状态失败:', error);
    ElMessage.error('切换菜单状态失败');
    // 恢复原始状态
    data.isActive = !data.isActive;
  }
}
</script>
<style scoped>
.menu-manage {
  display: flex;
  gap: 32px;
  align-items: flex-start;
}

.menu-tree-card {
  flex: 1;
  min-width: 340px;
}

.menu-tree-title {
  font-size: 18px;
  font-weight: bold;
  color: #2451a6;
  margin-bottom: 12px;
}

.menu-path {
  color: #999;
  font-size: 13px;
  margin-left: 6px;
}

.menu-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-left: auto;
  justify-content: flex-end;
  min-width: 120px;
}

.menu-item-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.menu-form-card {
  width: 420px;
}

.menu-form-title {
  font-size: 18px;
  font-weight: bold;
  color: #2451a6;
  margin-bottom: 12px;
}

.delete-button {
  background-color: #f56c6c;
  border-color: #f56c6c;
  color: #fff;
  transition: background-color 0.3s ease, border-color 0.3s ease;
}

.delete-button:hover {
  background-color: #e05a5a;
  border-color: #e05a5a;
}

.custom-message-box .el-message-box__header {
  background-color: #f5f5f5;
  border-bottom: 1px solid #eaeaea;
}

.custom-message-box .el-message-box__content {
  padding: 20px;
}

.custom-message-box .el-message-box__btns {
  text-align: right;
  padding: 10px 20px;
}

.custom-message {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
}

.cancel-button {
  background-color: #f0f2f5;
  border-color: #dcdfe6;
  color: #606266;
  transition: all 0.3s ease;
}

.cancel-button:hover {
  background-color: #e4e7ed;
  border-color: #c0c4cc;
  color: #303133;
}

.reset-button {
  background-color: #ecf5ff;
  border-color: #dcdfe6;
  color: #409eff;
  transition: all 0.3s ease;
}

.reset-button:hover {
  background-color: #e6f2ff;
  border-color: #90c8ff;
  color: #3078d6;
}

.add-button {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-button:hover {
  background-color: #3078d6;
  border-color: #3078d6;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.add-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(64, 158, 255, 0.2);
}

/* .menu-disabled-tag {
  margin-left: 8px;
  padding: 2px 6px;
  background-color: #ff4949;
  color: white;
  font-size: 12px;
  border-radius: 4px;
} */

:deep(.el-button--success.is-plain) {
  color: #67c23a;
  background-color: #f0f9eb;
  border-color: #c2e7b0;
}

:deep(.el-button--info.is-plain) {
  color: #909399;
  background-color: #f4f4f5;
  border-color: #d3d4d6;
}
</style>
